package com.kit.data.kitopeso.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.kit.data.kitopeso.PathMaping;
import com.kit.data.kitopeso.R;
import com.kit.data.kitopeso.adapter.IdentityAdapter;
import com.kit.data.kitopeso.base.BaseActivity;
import com.kit.data.kitopeso.base.BaseDialog;
import com.kit.data.kitopeso.base.BaseParams;
import com.kit.data.kitopeso.databinding.KitoIdentityItemBinding;
import com.kit.data.kitopeso.databinding.KitoOcrActivityBinding;
import com.kit.data.kitopeso.dialog.PhotoChooseDialog;
import com.kit.data.kitopeso.net.PU;
import com.kit.data.kitopeso.net.RxHttp;
import com.kit.data.kitopeso.net.U;
import com.kit.data.kitopeso.obj.KitoIdentity;
import com.kit.data.kitopeso.tools.AESCryptUtilJar;
import com.kit.data.kitopeso.tools.FileUtils;
import com.kit.data.kitopeso.tools.ImgUitls;
import com.kit.data.kitopeso.tools.JsonParse;
import com.kit.data.kitopeso.tools.LogUtil;
import com.kit.data.kitopeso.tools.ResUtils;
import com.kit.data.kitopeso.tools.SpUtils;
import com.kit.data.kitopeso.tools.Tools;
import com.kit.data.kitopeso.tools.ViewUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class KitoOcrActivity extends BaseActivity<KitoOcrActivityBinding> {


    IdentityAdapter adater;
    List<KitoIdentity> dataList;

    ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    private long clickStartTime = 0;

    private long clickEndTime = 0;


    PhotoChooseDialog mPhotoChooseDialog;


    @Override
    protected KitoOcrActivityBinding initViewBinding(LayoutInflater inflater) {
        return KitoOcrActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.tvHit1.setText(Html.fromHtml(ResUtils.s(R.string.ocr_hit1)));
        binding.tvHit.setText(Html.fromHtml(ResUtils.s(R.string.ocr_btn5)));
        binding.typeLayout3.setText(Html.fromHtml(ResUtils.s(R.string.ocr_title6)));


        binding.tvBox.setClickable(false);
        binding.tvBox.setFocusable(false);
        binding.hitLayout.setSelected(true);

        binding.hitLayout.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            if (binding.hitLayout.isSelected()) {
                binding.hitLayout.setSelected(false);
                binding.tvHit.setSelected(false);
                binding.tvBox.setChecked(false);
            } else {
                binding.hitLayout.setSelected(true);
                binding.tvHit.setSelected(true);
                binding.tvBox.setChecked(true);
            }
        });
        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P121, "");
            startActivity(new Intent(getActivity(), KitoCustomerServiceActivity.class));
        });
        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P196, "");
            PU.userBuriedAllPoint(getActivity());
            ocrInfo();
        });
        binding.getRoot().setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot()));
        binding.frontLayout.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            showPhotoChooseDialog(false);
        });
        binding.backLayout.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            showPhotoChooseDialog(true);
        });
        binding.typeLayout2.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            showPhotoChooseDialog(false);
        });

        binding.tvIndicate.removeAllViews();

        List<View> viewList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            View indicateView = new View(getActivity());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.dp_8), getResources().getDimensionPixelSize(R.dimen.dp_8));
            if (binding.tvIndicate.getChildCount() > 0) {
                layoutParams.leftMargin = getResources().getDimensionPixelSize(R.dimen.dp_6);
                indicateView.setBackground(ResUtils.de(R.drawable.indicate_un_selector));
            } else {
                indicateView.setBackground(ResUtils.de(R.drawable.indicate_selector));
            }
            indicateView.setLayoutParams(layoutParams);
            binding.tvIndicate.addView(indicateView);

            KitoIdentityItemBinding binding1 = KitoIdentityItemBinding.inflate(LayoutInflater.from(getActivity()));

            viewList.add(binding1.getRoot());
        }

        dataList = new ArrayList<>();
        KitoIdentity identity1 = new KitoIdentity();
        identity1.setTitle(getResources().getString(R.string.ocr_title1));
        identity1.setIcon(R.mipmap.ocr_icon1);
        identity1.setIcon1(R.mipmap.ocr_icon1_s);
        identity1.setType("PASSPORT");

        KitoIdentity identity2 = new KitoIdentity();
        identity2.setTitle(getResources().getString(R.string.ocr_title2));
        identity2.setIcon(R.mipmap.ocr_icon2);
        identity2.setIcon1(R.mipmap.ocr_icon2_s);
        identity2.setType("IDCARD");

        KitoIdentity identity3 = new KitoIdentity();
        identity3.setTitle(getResources().getString(R.string.ocr_title3));
        identity3.setIcon(R.mipmap.ocr_icon3);
        identity3.setIcon1(R.mipmap.ocr_icon3_s);
        identity3.setType("DRIVING");

        KitoIdentity identity4 = new KitoIdentity();
        identity4.setTitle(getResources().getString(R.string.ocr_title4));
        identity4.setIcon(R.mipmap.ocr_icon4);
        identity4.setIcon1(R.mipmap.ocr_icon4_s);
        identity4.setType("DRIVING");

        KitoIdentity identity5 = new KitoIdentity();
        identity5.setTitle(getResources().getString(R.string.ocr_title5));
        identity5.setIcon(R.mipmap.ocr_icon5);
        identity5.setIcon1(R.mipmap.ocr_icon5_s);
        identity5.setType("");

        dataList.add(identity2);
        dataList.add(identity1);
        dataList.add(identity3);
        dataList.add(identity4);
//        dataList.add(identity5);

        adater = new IdentityAdapter(viewList, dataList);
        binding.viewPager.setPageMargin(0);
        binding.viewPager.setAdapter(adater);
        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int childCount = binding.tvIndicate.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    View childView = binding.tvIndicate.getChildAt(i);
                    if (position == i) {
                        childView.setBackground(ResUtils.de(R.drawable.indicate_selector));
                    } else {
                        childView.setBackground(ResUtils.de(R.drawable.indicate_un_selector));
                    }
                }
                for (int i = 0; i < viewList.size(); i++) {
                    View view = viewList.get(i);
                    View childView = view.findViewById(R.id.tvRoot);
                    TextView title = view.findViewById(R.id.tvTitle);
                    if (position == i) {
                        childView.setSelected(true);
                        title.setSelected(true);
                    } else {
                        childView.setSelected(false);
                        title.setSelected(false);
                    }
                    if (i != position) {
                        view.setScaleX(0.8f);
                        view.setScaleY(0.8f);
                    } else {
                        view.setScaleX(1f);
                        view.setScaleY(1f);
                    }
                }

                switchTab(position);

                adater.setIndex(position);
                adater.notifyDataSetChanged();

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P119;
        UP_TYPE2 = PU.P120;
        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                String imgPath = FileUtils.getFileAbsolutePath(getActivity(), uri);
                imageUpload(uri, imgPath);
                LogUtil.e("me", "imgPath->" + imgPath);
                clickEndTime = System.currentTimeMillis();
                PU.userBuriedPoint(PU.P128, imgPath + "$$" + (clickEndTime - clickStartTime));
            }
        });
        switchTab(0);
    }

    void switchTab(int position) {


        binding.hitLayout.setVisibility(View.VISIBLE);
        binding.tvHit1.setVisibility(View.VISIBLE);



        if (position == 1) {

            binding.typeLayout.setVisibility(View.VISIBLE);
            binding.typeTitle.setText(ResUtils.s(R.string.ocr_title1));

            binding.typeLayout1.setVisibility(View.GONE);
            binding.typeLayout2.setVisibility(View.VISIBLE);
            binding.typeLayout3.setVisibility(View.GONE);


            binding.frontPhoto1.setVisibility(View.VISIBLE);
            binding.frontImg1.setImageResource(R.mipmap.ocr_front_img);

            binding.frontImg1Txt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImg1Cover.setVisibility(View.GONE);


            PU.userBuriedPoint(PU.P124, "");


        } else if (position == 0) {

            binding.typeLayout.setVisibility(View.VISIBLE);
            binding.typeTitle.setText(ResUtils.s(R.string.ocr_title2));

            binding.typeLayout1.setVisibility(View.VISIBLE);
            binding.typeLayout2.setVisibility(View.GONE);
            binding.typeLayout3.setVisibility(View.GONE);

            binding.frontPhoto.setVisibility(View.VISIBLE);
            binding.frontImg.setImageResource(R.mipmap.ocr_front_img);
            binding.backPhoto.setVisibility(View.VISIBLE);
            binding.backImg.setImageResource(R.mipmap.ocr_back_img);


            binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn1));
            binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImgCover.setVisibility(View.GONE);
            binding.backImgCover.setVisibility(View.GONE);


            PU.userBuriedPoint(PU.P122, "");


        } else if (position == 2) {

            binding.typeLayout.setVisibility(View.VISIBLE);
            binding.typeTitle.setText(ResUtils.s(R.string.ocr_title3));

            binding.typeLayout1.setVisibility(View.VISIBLE);
            binding.typeLayout2.setVisibility(View.GONE);
            binding.typeLayout3.setVisibility(View.GONE);

            binding.frontPhoto.setVisibility(View.VISIBLE);
            binding.frontImg.setImageResource(R.mipmap.ocr_front_img);
            binding.backPhoto.setVisibility(View.VISIBLE);
            binding.backImg.setImageResource(R.mipmap.ocr_back_img);


            binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn1));
            binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImgCover.setVisibility(View.GONE);
            binding.backImgCover.setVisibility(View.GONE);

            PU.userBuriedPoint(PU.P123, "");

        } else if (position == 3) {

            binding.typeLayout.setVisibility(View.VISIBLE);
            binding.typeTitle.setText(ResUtils.s(R.string.ocr_title4));

            binding.typeLayout1.setVisibility(View.VISIBLE);
            binding.typeLayout2.setVisibility(View.GONE);
            binding.typeLayout3.setVisibility(View.GONE);

            binding.frontPhoto.setVisibility(View.VISIBLE);
            binding.frontImg.setImageResource(R.mipmap.ocr_front_img);
            binding.backPhoto.setVisibility(View.VISIBLE);
            binding.backImg.setImageResource(R.mipmap.ocr_back_img);


            binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn1));
            binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn1));


            binding.frontImgCover.setVisibility(View.GONE);
            binding.backImgCover.setVisibility(View.GONE);

            PU.userBuriedPoint(PU.P125, "");

        } else if (position == 4) {


            binding.typeLayout.setVisibility(View.GONE);
            binding.typeLayout3.setVisibility(View.VISIBLE);

            binding.hitLayout.setVisibility(View.GONE);
            binding.tvHit1Layout.setVisibility(View.INVISIBLE);

            PU.userBuriedPoint(PU.P126, "");

        }

        binding.frontPhoto.setImageResource(R.mipmap.ocr_upload);
        binding.backPhoto.setImageResource(R.mipmap.ocr_upload);
        binding.frontImgTxt.setCompoundDrawablesWithIntrinsicBounds(0,0, 0, 0);
        binding.backImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

    }

    void loadData(String url) {

        if (getActivity() != null && !isFinishing()) {

            int position = adater.getIndex();

            KitoIdentity identity = null;

            if (dataList.size() > position && position != 4) {
                identity = dataList.get(position);
            }

            LogUtil.e("me", url + "<-position->" + position);

            if (identity == null) {
                return;
            }

            if (!TextUtils.isEmpty(url)) {
                if (position == 1) {
                    identity.setCardImgUrl(url);
                    Glide.with(getActivity()).load(url).placeholder(R.color.placeholder_icon).into(binding.frontImg1);
                    binding.frontPhoto1.setVisibility(View.GONE);
                    binding.frontImg1Cover.setVisibility(View.VISIBLE);
                    binding.frontImg1Txt.setText(ResUtils.s(R.string.ocr_btn2));
                    binding.frontImg1Txt.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ocr_reset, 0, 0);
                    binding.frontImg1Txt.setTextColor(Color.parseColor("#FFFFFF"));
                } else {

                    if (identity.isBack()) {
                        identity.setCardBackImgUrl(url);
                        binding.backPhoto.setVisibility(View.GONE);
                        Glide.with(getActivity()).load(url).placeholder(R.color.placeholder_icon).into(binding.backImg);
                        binding.backImgCover.setVisibility(View.VISIBLE);
                        binding.backImgTxt.setText(ResUtils.s(R.string.ocr_btn2));
                        binding.backImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ocr_reset, 0, 0);
                        binding.backImgTxt.setTextColor(Color.parseColor("#FFFFFF"));
                    } else {
                        identity.setCardImgUrl(url);
                        binding.frontPhoto.setVisibility(View.GONE);
                        Glide.with(getActivity()).load(url).placeholder(R.color.placeholder_icon).into(binding.frontImg);
                        binding.frontImgCover.setVisibility(View.VISIBLE);
                        binding.frontImgTxt.setText(ResUtils.s(R.string.ocr_btn2));
                        binding.frontImgTxt.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.ocr_reset, 0, 0);
                        binding.frontImgTxt.setTextColor(Color.parseColor("#FFFFFF"));
                    }


                }
            }

        }
    }

    void showPhotoChooseDialog(boolean isBack) {
        int position = adater.getIndex();
        if (position != -1 && position < dataList.size()) {
            KitoIdentity identity = dataList.get(position);
            if (identity != null) {
                identity.setBack(isBack);
            }
        }
        if (mPhotoChooseDialog == null) {
            mPhotoChooseDialog = new PhotoChooseDialog(this);
        }
        mPhotoChooseDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                int type = mPhotoChooseDialog.getType();
                if (type == 1) {
                    toTakePhoto();
                } else if (type == 2) {
                    formAlbum();
                }
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
        mPhotoChooseDialog.show();
    }

    void toTakePhoto() {
        clickStartTime = System.currentTimeMillis();
        Intent intent = new Intent(this, KitoCameraActivity.class);
        someActivityResultLauncher.launch(intent);
    }


    void formAlbum() {
        clickStartTime = System.currentTimeMillis();
        if (pickMedia != null) {
            pickMedia.launch(new PickVisualMediaRequest.Builder()
                    .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                    .build());
        }
    }

    final ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                LogUtil.e("me", "--onActivityResult--");
                if (result.getResultCode() == RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        String url = data.getStringExtra("url");
                        LogUtil.e("me", "onActivityResult url->" + url);
                        if (!TextUtils.isEmpty(url)) {
                            loadData(url);
                        }
                        PU.userBuriedPoint(PU.P127, url + "$$" + (clickEndTime - clickStartTime));
                    }
                }
            }
    );


    void ocrInfo() {

        int position = adater.getIndex();
        String faceImgUrl;
        String cardImgUrl;
        String cardBackImgUrl;
        String cardType;
        if (position != 4) {

            KitoIdentity identity = null;

            if (position < dataList.size()) {
                identity = dataList.get(position);
            }

            if (identity == null) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_info_tips1));
                return;
            }
            faceImgUrl = identity.getFaceImgUrl();
            cardImgUrl = identity.getCardImgUrl();
            cardBackImgUrl = identity.getCardBackImgUrl();
            cardType = identity.getType();

            LogUtil.e("me", cardBackImgUrl + "--ocrInfo--" + identity.isBack() + "," + cardImgUrl);

            if ((identity.getType().equals("IDCARD") || identity.getType().equals("DRIVING")) && TextUtils.isEmpty(cardImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_info_tips2));
                return;
            }
            if ((identity.getType().equals("IDCARD") || identity.getType().equals("DRIVING")) && TextUtils.isEmpty(cardBackImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_info_tips3));
                return;
            }
            if (identity.getType().equals("PASSPORT") && TextUtils.isEmpty(cardImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_info_tips2));
                return;
            }

            if (identity.getType().equals("FACE") && TextUtils.isEmpty(faceImgUrl)) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.ocr_info_tips4));
                return;
            }
        } else {
            faceImgUrl = "https://test.png";
            cardImgUrl = "https://test.png";
            cardBackImgUrl = "https://test.png";
            cardType = "IDCARD";
        }
        showLoading("");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[53]);
        json.addProperty("cardType", cardType);
        json.addProperty("faceImgUrl", faceImgUrl);
        json.addProperty("cardImgUrl", cardImgUrl);
        json.addProperty("cardBackImgUrl", cardBackImgUrl);


        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }

        String data = AESCryptUtilJar.encryptDefault(json.toString());

        LogUtil.e("me", json + "<-ocrInfo post->" + data);

        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (binding != null) {
                            hideLoading();
                            if (!TextUtils.isEmpty(s)) {
                                String json1 = AESCryptUtilJar.decryptDefault(s);
                                if (JsonParse.getCode(json1)) {
                                    String token = JsonParse.ocrInfoJson2Obj(json1);
                                    LogUtil.e("me", "ocrInfo json->" + token);
                                    if (!TextUtils.isEmpty(token)) {
                                        userProcess(() -> {
                                            if (binding.tvBox.isSelected() && position != 4) {
                                                Toast.makeText(getActivity(), getResources().getString(R.string.ocr_info_tips5), Toast.LENGTH_LONG).show();
                                            }
                                            boolean isCheckSteps = checkSteps();
                                            if (!isCheckSteps) {
                                                startActivity(new Intent(getActivity(), KitoApplyActivity.class));
                                            }
                                            finish();
                                        }, true);
                                    }
                                } else {
                                    showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (binding != null) {
                            hideLoading();
                            showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.login_faile));
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    void imageUpload(Uri imageUri, String path) {
        showLoading(ResUtils.s(R.string.upload));
        LogUtil.e("me", "URL.uploadUrl->" + U.uploadUrl);
        RxHttp.uploadImage(U.uploadUrl, ImgUitls.compressToTargetSize(this, imageUri, 1024, path))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (!TextUtils.isEmpty(s)) {
                            String url = JsonParse.imageUploadJson2Obj(s);
                            LogUtil.e("me", "imageUpload url->" + url);
                            if (!TextUtils.isEmpty(url)) {
                                showToastDialog(R.mipmap.hit_icon1, ResUtils.s(R.string.upload_completed));
                                loadData(url);
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (e != null) {
                            LogUtil.e("me", "imageUpload e->" + e);
                        }
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, ResUtils.s(R.string.upload_failed));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPhotoChooseDialog != null) {
            mPhotoChooseDialog.dismiss();
        }
    }


}
